
    /٢iʉ                     N   d dl Z d dlZd dlZd dlmZmZ d dlmZ d dlmZm	Z	m
Z
mZ  ej                  e      Zdededz  fdZdadedz  fdZdadefd	Zdadefd
Zi dddddddddddddddddddddddddddddddddddd d!dddd"dd#d$dddddd%d&dddd'dd(d)dddd*dd+d,dddd-dd.d/dddd0dd1d2d3d4dd*dd5d6d3d4d7d*dd8d9d3d4d7d*dd:d;d3d<dd-dd=d>d?d4d@dAddBdCd?d4d@dAdi dDdEd?d4d@dAddFdGd?d4d@dAddHdId?d4d@dAddJdKdLdMdd'ddNdOdLdMddPddQdRdLdSdd'ddTdUdLdMdd-ddVdWdLdXdd-ddYdZdLdMdd'dd[d\dLdMdddd]d^dLdMdd'dd_d`dadbddcddddedadddcddfdgdadbddcddhdidjdbddkddldmdjdbddkddndodjdbddkdZdpddqdrdsdtd*dudvdsdwdAdxdydsdzd'd{d|dsd}dcd~ddsddkdddsdZdZdedefdZ e e	d       e
ddd       ee      d      ddedededededefd       Zddededededef
dZi ddddddddddd dd#dd%dd(dd+dd.dd1dd5dd8dd:dd=ddBdi dDddFddHddJddNddQddTddVddYdd[dd]dd_dddddfddhddlddndZdedefdZ ddedededededefdZ!dedefdZ"ddedededededefdZ#y)    N)datetimetimezone)OpenAI)retrystop_after_attemptwait_exponentialretry_if_exceptionkeysreturnc                  \    | D ]'  }t         j                  j                  |      }|s%|c S  y N)osenvironget)r
   keyvals      8/sites/domain-asset-master/app/services/business_docs.py_resolve_envr      s0     jjnnS!J     c                  x    t         /t        dd      } | r!t        d      }d| i}|r||d<   t        di |a t         S NAI_INTEGRATIONS_OPENAI_API_KEYOPENAI_API_KEYAI_INTEGRATIONS_OPENAI_BASE_URLapi_keybase_url _clientr   r   r   r   kwargss      r   _get_openai_clientr"      L    ?AQR#$EFH)F%-z"&v&GNr   c                  x    t         /t        dd      } | r!t        d      }d| i}|r||d<   t        di |a t         S r   r   r    s      r   r"   r"   %   r#   r   c                  x    t         /t        dd      } | r!t        d      }d| i}|r||d<   t        di |a t         S r   r   r    s      r   r"   r"   4   r#   r   business_planzBusiness Planbusiness_docsg      ? @  	briefcase)labeltiertemperature
max_tokensiconsop_customer_onboardingzSOP: Customer Onboardingg?i    userssop_lead_generationzSOP: Lead Generationtargetsop_sales_processzSOP: Sales Processchartsop_project_deliveryzSOP: Project Deliverychecksop_customer_servicezSOP: Customer Serviceheartsop_financial_managementzSOP: Financial Managementsop_marketingzSOP: Marketing Operations	megaphonesop_data_securityzSOP: Data Securityshieldsop_employee_trainingzSOP: Employee Trainingbooksop_crisis_managementzSOP: Crisis Managementzap	legal_ndazNon-Disclosure Agreementlegalg?legal_privacy_policyzPrivacy Policy (GDPR/CCPA)i 0  legal_terms_of_servicezTerms of Servicelegal_employee_handbookzEmployee Handbookg333333?contract_servicezService Agreement	contractsi (  z	file-textcontract_consultingzConsulting Agreementcontract_projectzProject-Based Contractcontract_retainerzRetainer Agreementcontract_licensezLicense Agreementmarketing_email_campaignzEmail Campaign Templates	marketingg?marketing_social_calendarzSocial Media Calendarcalendarmarketing_press_releasezPress Release Templategffffff?marketing_case_studyzCase Study Templatemarketing_blog_postszBlog Post Templatesg      ?marketing_newsletterzNewsletter Templatemarketing_linkedin_outreachzLinkedIn Outreachmarketing_cold_emailzCold Email Sequencesops_virtual_officezVirtual Office Setup Guide
operationsg333333?cogops_business_registrationzBusiness Registration Guideops_crm_recommendationzCRM Recommendationcalculator_pricingzPricing Calculator Configcalculators
calculatorcalculator_estimatezEstimate Generator Configcalculator_quote_pipelinezQuote-to-Proposal PipelinezBusiness Documentsz#3B82F6z#Plans, SOPs, and operational guides)r*   r.   colordescriptionzLegal & Compliancez#EF4444z(NDAs, privacy policies, terms, contractszClient Contractsz#F59E0Bz5Service, consulting, retainer, and license agreementszMarketing Arsenalz#8B5CF6z.Email campaigns, social media, press, outreachzOperations Toolkitz#10B981z'Virtual office, registration, CRM setupzCalculators & Quotingz#EC4899z4Pricing tools, estimates, quote-to-proposal pipeline)r'   rC   rH   rN   rX   r]   u  You are a Fortune 500-caliber business consultant, legal strategist, and operations architect. You produce board-ready, niche-specific business documents that are immediately actionable — not generic templates.

ROLE & AUTHORITY
- You write as though retained at $500/hour by the company described in the prompt.
- Every document must reflect the SPECIFIC niche, market dynamics, competitive landscape, and operational realities of the business described.
- Documents must be ready to use with minimal editing — not skeleton outlines.

QUALITY STANDARDS
- BANNED phrases: "cutting-edge", "state-of-the-art", "revolutionary", "game-changing", "leverage", "synergy", "best-in-class", "world-class", "innovative solution", "streamline", "holistic approach".
- REQUIRED: Concrete specifics, measurable KPIs, real timelines, actionable steps with owners and deadlines.
- Every SOP must include: purpose, scope, responsible parties, step-by-step procedures, escalation paths, metrics, and review cadence.
- Every legal document must include: proper clause numbering, defined terms, jurisdiction awareness, and practical enforceability.
- Every contract must include: scope of work framework, payment terms, IP ownership, termination clauses, and dispute resolution.
- Every marketing document must include: audience segmentation, specific messaging angles, conversion metrics, and A/B testing suggestions.

PERSONALIZATION MARKERS
Use these placeholder markers throughout documents for easy client customization:
- [COMPANY_NAME] — the business name
- [COMPANY_ADDRESS] — business address
- [STATE] — state of incorporation/operation
- [DATE] — effective date
- [CLIENT_NAME] — client/counterparty name
- [CLIENT_ADDRESS] — client address
- [REPRESENTATIVE_NAME] — authorized representative
- [REPRESENTATIVE_TITLE] — representative's title
- [WEBSITE_URL] — company website
- [EMAIL] — company email
- [PHONE] — company phone

OUTPUT FORMAT
Return the document as well-structured Markdown with proper headings (##, ###), numbered lists for procedures, tables where appropriate (pricing, timelines, comparisons), and clear section breaks. Do NOT wrap the output in code fences or JSON — return raw Markdown text.

NICHE SPECIFICITY
- Reference actual industry terminology, common tools, typical price points, and realistic timelines for the specific niche.
- Include niche-specific risks, compliance requirements, and competitive considerations.
- Tailor all examples, scenarios, and metrics to the business type described.

DEPTH REQUIREMENTS
- Business plans: Include executive summary, market analysis, competitive positioning, revenue model, financial projections framework, marketing strategy, operations plan, and milestones.
- SOPs: Include purpose, scope, definitions, responsibilities (RACI where applicable), detailed step-by-step procedures, exception handling, quality checks, metrics/KPIs, review schedule.
- Legal documents: Include proper legal structure, defined terms, numbered clauses, jurisdiction-aware language, severability, entire agreement, amendment procedures.
- Contracts: Include recitals, definitions, scope, deliverables framework, payment terms, warranties, indemnification, limitation of liability, IP ownership, confidentiality, termination, governing law.
- Marketing materials: Include audience personas, messaging frameworks, specific copy variations, CTAs, timing recommendations, success metrics.
- Operations guides: Include tool recommendations with pros/cons, setup procedures, cost breakdowns, integration steps, maintenance schedules.
- Calculators: Include pricing model structure, cost categories, margin calculations, competitive positioning rationale, discount tiers.	exceptionc                     t        |       }d|v xsL d|v xsF d|j                         v xs2 d|j                         v xs t        | d      xr t        | dd       dk(  S )N429RATELIMIT_EXCEEDEDquotaz
rate limitstatus_codei  )strlowerhasattrgetattr)rc   	error_msgs     r   _is_rate_limit_errorrn      sy    II 	b9,	bioo''	b 9??,,	b I}-`')]TX2Y]`2`r            <   )
multiplierminmaxT)stopwaitr   reraisepromptsystem_promptr,   r-   	json_modec                    g }|r|j                  d|d       |j                  d| d       d|||d}|rddi|d<   t               }|st        j                  d	       y
 |j                  j
                  j                  di |}|st        j                  d	       y
 |j                  j
                  j                  di |}|j                  d   j                  j                  xs d
S )Nsystem)rolecontentuserzgpt-4o)modelmessagesmax_completion_tokensr,   typejson_objectresponse_formatzHOpenAI client not initialized because API key is not set. Skipping call. r   r   )
appendr"   loggerwarningchatcompletionscreatechoicesmessager   )	ry   rz   r,   r-   r{   r   r!   clientresponses	            r   _call_with_temperaturer      s     HmDEOOV78 !+"	F %+]$; !!Fab-v{{&&--77Hab-v{{&&--77HA&&..4"4r   domainniche
brand_data	discoveryc                 j   d}d}|r]|j                  dg       }|j                  dd      }|r7t        |      |kD  r)||   }|j                  d|      }|j                  dd      }dd	|  d
| d| g}	|r|	j                  d|        |r|j                  d      r|	j                  d|d           |j                  d      r|	j                  d|d           |j                  d      r|	j                  d|d           |j                  d      r|	j                  d|d           |j                  d      r|	j                  d|d           |j                  d      r|	j                  d|d           |j                  d      r|	j                  d|d           dj                  |	      S )Nz[COMPANY_NAME]r   optionsrecommended_indexr   nametaglinezBUSINESS CONTEXT:z
- Domain: z- Business Niche: z- Brand Name: z- Tagline: visionz
- Vision: audiencez- Target Audience: positioningz- Positioning: servicesz- Services/Products: competitorsz- Known Competitors: pricing_rangez- Pricing Range: locationz- Location/Region: 
)r   lenr   join)
r   r   r   r   
brand_namer   r   rec_idxchosenliness
             r   _build_brand_contextr      s   !JG..B/..!4a8s7|g-W%FFJ7JjjB/G 
VH
UG$
%	E {7),-=="LL:i&9%:;<==$LL.y/D.EFG=='LL?9]+C*DEF==$LL0:1F0GHI=='LL0=1I0JKL==)LL,Y-G,HIJ==$LL.y/D.EFG99Ur   a  Generate a comprehensive Business Plan. Include: Executive Summary, Company Overview, Market Analysis (TAM/SAM/SOM for this niche), Competitive Landscape, Products/Services, Marketing & Sales Strategy, Operations Plan, Management Team Framework, Financial Projections Framework (Year 1-3 revenue model, cost structure, break-even analysis), Key Milestones & Timeline, Risk Assessment with mitigation strategies.ao  Generate a detailed Standard Operating Procedure for Customer Onboarding. Cover: initial contact and welcome sequence, needs assessment process, account setup procedures, kickoff meeting agenda template, expectations setting, communication cadence, handoff procedures between sales and delivery, 30/60/90-day check-in framework, success metrics, and escalation paths.aI  Generate a detailed SOP for Lead Generation. Cover: inbound and outbound channels specific to this niche, lead scoring criteria, qualification frameworks (BANT/MEDDIC adapted for niche), CRM pipeline stages, follow-up cadences, content marketing triggers, referral program structure, conversion benchmarks, and reporting cadence.aT  Generate a detailed SOP for the Sales Process. Cover: prospecting methods for this niche, discovery call framework, proposal creation process, objection handling playbook with niche-specific objections, pricing presentation strategy, negotiation guidelines, close procedures, win/loss analysis, and commission/incentive structure framework.aC  Generate a detailed SOP for Project Delivery. Cover: project initiation and scoping, resource allocation, milestone planning, client communication protocols, quality assurance checkpoints, change request procedures, deliverable acceptance criteria, project closure and retrospective process, and documentation requirements.a=  Generate a detailed SOP for Customer Service. Cover: support channel setup (email/phone/chat), ticket classification and priority matrix, response time SLAs by priority, escalation tiers and procedures, knowledge base maintenance, CSAT/NPS measurement, complaint resolution framework, and proactive outreach triggers.aL  Generate a detailed SOP for Financial Management. Cover: invoicing procedures and payment terms, accounts receivable follow-up cadence, expense approval workflow, monthly close procedures, cash flow monitoring, tax preparation checklist, financial reporting schedule, budget vs. actual review process, and vendor payment procedures.aU  Generate a detailed SOP for Marketing Operations. Cover: content calendar management, campaign planning and approval workflow, brand guidelines enforcement, analytics and reporting cadence, social media posting procedures, email marketing workflows, SEO monitoring, paid advertising management, and marketing asset creation/approval process.aa  Generate a detailed SOP for Data Security. Cover: data classification framework, access control procedures, password and authentication policies, incident response plan, data backup and recovery procedures, employee security training requirements, vendor security assessment, compliance monitoring (GDPR/CCPA as applicable), and security audit schedule.aa  Generate a detailed SOP for Employee Training. Cover: onboarding training curriculum, role-specific skill requirements, training schedule and delivery methods, knowledge assessment procedures, mentorship program structure, continuing education requirements, performance-based training triggers, training material maintenance, and certification tracking.a[  Generate a detailed SOP for Crisis Management. Cover: crisis classification matrix (severity levels), communication chain of command, initial response procedures by crisis type, stakeholder notification templates, media response guidelines, business continuity activation triggers, post-crisis review process, and crisis simulation/drill schedule.a  Generate a comprehensive Non-Disclosure Agreement. Include: parties and recitals, definition of confidential information (broad and niche-specific), exclusions from confidentiality, obligations of receiving party, permitted disclosures, term and termination, return/destruction of information, remedies for breach, non-solicitation clause, governing law, entire agreement, and signature blocks.a  Generate a comprehensive Privacy Policy compliant with GDPR and CCPA. Include: information collected (specific to niche), how information is used, legal bases for processing, cookies and tracking technologies, third-party sharing and service providers, data retention periods, user rights (access, deletion, portability, opt-out), children's privacy, international transfers, security measures, policy updates, and contact information for privacy inquiries.a  Generate comprehensive Terms of Service. Include: acceptance of terms, description of services, user accounts and responsibilities, payment terms and refund policy, intellectual property rights, user-generated content (if applicable), prohibited uses, disclaimers and limitation of liability, indemnification, dispute resolution (arbitration clause), governing law, modifications to terms, termination, severability, and contact information.a  Generate a comprehensive Employee Handbook. Include: welcome and company culture, employment classifications, equal opportunity policy, compensation and benefits overview, work schedule and attendance, remote work policy, PTO and leave policies, code of conduct, anti-harassment policy, performance review process, disciplinary procedures, grievance procedures, technology and social media policy, confidentiality obligations, separation procedures, and acknowledgment form.a  Generate a comprehensive Service Agreement. Include: recitals, definitions, scope of services (framework with blanks for specifics), service levels and KPIs, client responsibilities, fees and payment terms, term and renewal, change orders, warranties, indemnification, limitation of liability, insurance requirements, confidentiality, IP ownership, termination for cause and convenience, transition assistance, force majeure, governing law, dispute resolution, and signature blocks.a  Generate a comprehensive Consulting Agreement. Include: engagement scope and objectives, consultant responsibilities and deliverables, client obligations, compensation (hourly/project/retainer options), expense reimbursement, timeline and milestones, independent contractor status, confidentiality and non-compete, IP assignment, warranties, indemnification, insurance, termination provisions, and governing law.a  Generate a comprehensive Project-Based Contract. Include: project description and objectives, detailed scope of work framework, deliverables and acceptance criteria, project timeline and milestones, payment schedule tied to milestones, change order procedures, project team and responsibilities, communication protocols, quality standards, warranty period, IP ownership, risk allocation, termination, and dispute resolution.ay  Generate a comprehensive Retainer Agreement. Include: scope of retained services, monthly retainer fee and included hours, overage rates, rollover policy, response time commitments, reporting requirements, quarterly review process, scope adjustments, payment terms, term and renewal, termination notice period, transition period obligations, confidentiality, and IP provisions.a  Generate a comprehensive License Agreement. Include: grant of license (scope, territory, exclusivity), license restrictions, sublicensing rights, fees and royalties structure, payment terms, IP ownership and protection, quality control provisions, representations and warranties, indemnification, limitation of liability, term and renewal, termination events, effects of termination, audit rights, governing law, and dispute resolution.aa  Generate Email Campaign Templates for this niche. Include: welcome/onboarding sequence (5 emails), nurture sequence (7 emails), re-engagement sequence (3 emails), promotional campaign template, and post-purchase follow-up sequence. For each email provide: subject line (with A/B variant), preview text, body copy, CTA, send timing, and audience segment.aa  Generate a 30-Day Social Media Calendar. Include: daily post themes, platform-specific content (LinkedIn, Instagram, Facebook, Twitter/X), post copy with hashtag sets, content type (image/video/carousel/text), posting times, engagement prompts, content pillar rotation, and monthly performance review template. Tailor all content to this specific niche.ak  Generate Press Release Templates. Include: company launch press release, product/service announcement, partnership announcement, milestone/award announcement, and community involvement release. For each: headline formula, subheadline, dateline, body structure (inverted pyramid), boilerplate, contact information section, and distribution channel recommendations.a^  Generate a Case Study Template Framework. Include: title formulas, client overview section, challenge/problem statement, solution description, implementation process, results with specific metric frameworks, client testimonial prompt, key takeaways, and CTA. Also include an interview question guide for gathering case study information from clients.aj  Generate Blog Post Templates and Content Strategy. Include: 10 niche-specific blog post outlines with titles, meta descriptions, target keywords, word count targets, header structure, key points to cover, internal/external linking strategy, CTA placement, and content upgrade ideas. Cover a mix of educational, comparison, how-to, and thought leadership formats.aX  Generate a Newsletter Template and Content Plan. Include: newsletter structure/layout, subject line formulas, content sections (industry news, tips, featured content, CTA), frequency recommendation, segmentation strategy, growth tactics, engagement metrics to track, and 12 themed newsletter editions with topic outlines specific to this niche.av  Generate LinkedIn Outreach Sequences. Include: connection request templates (5 variants by persona), follow-up message sequence (5 touches), content engagement strategy, InMail templates, group participation strategy, thought leadership posting plan, and profile optimization checklist. All messaging must be natural and non-spammy, tailored to this niche's decision-makers.aX  Generate Cold Email Sequences. Include: initial outreach sequence (5 emails over 21 days), referral request template, breakup email, re-engagement sequence, and meeting confirmation flow. For each: subject line with A/B variant, body copy, personalization tokens, CTA, send timing, and follow-up triggers. Include deliverability best practices.a  Generate a Virtual Office Setup Guide. Include: business address service recommendations, virtual phone system setup, professional email configuration, video conferencing toolkit, cloud storage and file management, project management tool recommendations, accounting software setup, CRM selection criteria, team communication platform, and cybersecurity essentials. Include cost estimates and tool comparison tables.az  Generate a Business Registration Guide. Include: entity type comparison (LLC, S-Corp, C-Corp) with pros/cons for this niche, state registration steps, EIN application process, business license and permit requirements specific to this niche, DBA filing, business bank account setup, insurance requirements, trademark considerations, and compliance calendar with filing deadlines.ai  Generate a CRM Recommendation and Setup Guide. Include: CRM comparison matrix (HubSpot, Salesforce, Pipedrive, etc.) with feature analysis for this niche, recommended choice with justification, pipeline stage configuration, custom field setup, automation workflows, email integration, reporting dashboard setup, team training plan, and data migration checklist.a  Generate a Pricing Calculator Configuration. Include: pricing model analysis for this niche (hourly/project/value/subscription), cost structure breakdown (direct costs, overhead, profit margin targets), competitive pricing research framework, pricing tiers with feature differentiation, discount policies, annual vs. monthly pricing, enterprise/custom pricing triggers, and price increase communication templates.at  Generate an Estimate Generator Configuration. Include: service/product catalog with unit pricing, labor rate calculations, materials/resource cost templates, scope complexity multipliers, timeline impact on pricing, rush/priority surcharges, volume discount tiers, estimate template with line items, terms and validity period, and estimate-to-proposal conversion workflow.aj  Generate a Quote-to-Proposal Pipeline Configuration. Include: quote request intake form, qualification scoring, quote generation workflow, approval thresholds, proposal template structure, presentation guidelines, follow-up cadence, negotiation parameters (discount authority, term flexibility), win/loss tracking, and pipeline analytics dashboard configuration.tier_keyc                 t    t         j                         D cg c]  \  }}|d   | k(  rd|i| c}}S c c}}w )Nr+   r   )DOC_REGISTRYitems)r   doc_keydoc_metas      r   get_tier_doc_typesr   &  sH     ".!3!3!5GXFx' 
$8$  s   4doc_typec                    | t         vr,t        d|  dt        t         j                                      t         |    }t        j                  d|d    d| d| d|d    d		       t        ||||      }t        j                  | d
|d    d      }| d|d    d| d| d| d| d}	 t        |t        |d   |d         }	| |d   |d   |d   |	t        j                  t        j                         j#                         |d   ||d	}t        j                  d|d    d| dt%        |	       d       |S # t        $ r$}
t        j                  d|  d| d|
         d }
~
ww xY w)NzUnknown document type: . Available: Generating r*   z for z	 (niche: z, temp: r,   )zGenerate a comprehensive z
 document.z

DOCUMENT REQUEST: z

z+

Ensure every section is specific to the "u   " niche. Reference actual industry practices, typical price points, common tools, and realistic timelines for this type of business. Do not produce a generic template — produce a ready-to-use document that a z business operating via z_ could adopt immediately with minimal customization beyond filling in the [PLACEHOLDER] fields.r-   )ry   rz   r,   r-   zLLM call failed for z (z): r+   r.   )	r   titler+   r.   r   generated_atr,   r   r   zSuccessfully generated z chars))r   
ValueErrorlistr
   r   infor   _DOC_PROMPT_INSTRUCTIONSr   r   SYSTEM_PROMPT_BUSINESS_DOCS	Exceptionerrorr   nowr   utc	isoformatr   )r   r   r   r   r   metabrand_contextdoc_instructionry   r   eresults               r   generate_documentr   .  s   |#28*M$|O`O`ObJcIdeff!D
KK+d7m_E&5'RVWdReQffghi(
INM.228?XY]^eYfXggq=rsO !=/ "  **/  1C  DI  CJ  Jb  ci  bj  jILF	(5]+L)	
 gVV X\\2<<>M*
F KK)$w-fXRG~U\]^M#  +H:Rxs1#FGs   )D6 6	E#?EE#business_boxc           
      R   | si } | j                  di       }i }d}d}g d}t        j                         D ]  \  }}t        |      }t	        |      }	g }
g }|D ]2  }|d   |v r|
j                  |d          |j                  |d          4 t	        |
      }t        |	dkD  r||	z  dz  ndd      }||z  }||	z  }|d   |d   |d	   |||	|
|d
||<    t        |dkD  r||z  dz  ndd      }t        d|dz  dz  z   d      }d}g }|D ]<  }||vr&|t        v r|j                  dt        |   d           t	        |      dk\  s< n t	        |      dk  rKt        j                         D ]4  \  }}||vr||vr|j                  d|d           t	        |      dk\  s4 n |||||||dS )N	documentsr   )r&   rB   rD   rE   rG   r/   rM   r\   r   d   rp   r*   r.   ra   )r*   r.   ra   score	generatedtotalgenerated_keysmissing_keysg      ?g      Y@g      "@g      $@z	Generate    )total_scoretotal_generatedtotal_possibletier_scoresforce_multiplierpotential_multipliernext_actions)r   TIERSr   r   r   r   roundr   )r   docsr   r   r   priority_docsr   	tier_metatier_doc_types
tier_totalgenerated_itemsmissing_itemsdttier_generated
tier_scorer   r   r   r   priority_keyr   r   s                         r   calculate_maximization_scorer   \  s@   K,DKONM  %{{} 
)+H5(
  	0B%yD &&r%y1$$RY/		0 _-*q.NZ7#=VWYZ[
>)*$ w'f%w''-)	!
H#
8 NUVDV>9C?\]_`aKSK%$73#>>BL% t#(D)L,Fw,O+P QR|!	 <1!-!3!3!5 	GXd"wm'C##i0A/B$CD< A%		 #*(", 4$ r   c                    | t         vr,t        d|  dt        t         j                                      t	        |       }t        |      }i }i }	t        j                  d|  d| d|        t        |      D ]W  \  }
}|d   }|r	  |d|d    d	|
|       	 t        |||||      }|||<   t        j                  d|
dz    d| d|d           Y |r	  |dt         |    d    ||       t        j                  d|  dt        |       dt        |	       d       | t         |    d   ||	t        |      |t        j                  t         j"                        j%                         dS # t        $ r"}t        j                  d
|        Y d }~d }~ww xY w# t        $ r@}t        j                  d|
dz    d| d|d    d|        t        |      |	|<   Y d }~cd }~ww xY w# t        $ r Y w xY w)NzUnknown tier: r   z$Starting batch generation for tier 'z' (u    documents) — domain: r   r   r*   z...zProgress callback error: [rp   /z] Generated z] Failed to generate z: z
Completed zTier 'z' complete: z succeeded, z failed)r+   
tier_labelr   errorsgenerated_counttotal_countcompleted_at)r   r   r   r
   r   r   r   r   	enumerater   r   r   r   ri   r   r   r   r   r   )r   r   r   r   r   progress_callbackr   r   resultsr   idxr   r   cb_errr   r   s                   r   generate_tierr     s   u>(=ejjlAS@TUVV'1NEGF
KK6xjE7Jbcibjkl^, %RU)E!K7}C"@#uM	%&wz9UF%GGKK!C!G9AeWLGFG%" 	
5?7+C*DEueT KK&
,s7|nLVU\]^ Hog.w< X\\2<<> '  E!:6(CDDE  	%LL1S1WIQug-B2g;-rRSQTUV!!fF7O	%  		sB   E)8FG# )	F2FF	G  5GG #	G0/G0)r(   Fr   )NN)$r   jsonloggingr   r   openair   tenacityr   r   r   r	   	getLogger__name__r   ri   r   r   r"   r   r   r   BaseExceptionboolrn   floatintr   dictr   r   r   r   r   r   r   r   r   r   <module>r     s	   	   '  T T			8	$ d
  FTM  F  F 4#X\lq  |G  H#)C_mp  AE  OV   W# %;_ehx|  GO  P# #7adtx  CJ  K	#
 &=gjz~  IP  Q# &=gjz~  IP  Q# *Eor  CG  QX  !Y# :Odgw{  FQ  R# #7adtx  CK  L# '?il  }A  KQ  R# '?il  }A  KP  Q# 5wWZjn  yA  B# &BGdgw|  GO  P# (:G\_ot  G  H# )<g^brw  BH   I#  "5{[^ns  ~I  J!#" %;[adty  DO  P##$ ":K`csx  CN  O%#& #7]`pu  @K  L'#( "5{[^ns  ~I  J)#* *Dkjm  ~B  LW  !X+#,  +BKhk{  JT  "U-#. )A;gk{  JU   V/#0 &;[adtx  CI  J1#2 &;[adtx  CI  J3#4 &;[adtx  CN  O5#6 "-@+fiy}  HO  $P7#8 &<kbeuy  DO  P9#: $@,gjz~  IN  O;#<  +HR^or  CG  QV  "W=#> (<lcfvz  EJ  K?#@ $?gjz~  IU  VA#B %@-hk{  JV  WC#D  +GQ^or  CG  Q]  "^E#L  4[S\  nS  T+X	  cM  N-{Y  h_  `.i  iY  Z0%)  eN  O4lU^  pf  g	,L ^M d  	A		QA2	6
1
2	53 5s 5 5\_ 5tx 5  FI 55:$ $S $d $t $_b $N#  s#   Q#   g#   p	#
   b#   \#   !o#   m#   }#   A#   {#   ^#   h#   Z#    |#    }!#"   z##$   C%#&   U'#(   O)#*   !D+#,    "E-#.    M/#0   }1#2   I3#4   w5#6 "  $\7#8   w9#:   };#<    "^=#>   J?#@   zA#B   RC#D    "NE# L  + +S + +$ +[_ +ko +\Ft F FR,C , ,S ,d ,W[ ,  @D ,r   