#!/usr/bin/env python3
"""
Test script for AI enrichment proposal workflow.
Creates a test proposal for Waterm company.
"""
import sys
import os

# Setup path for production environment
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from dotenv import load_dotenv
# Load .env from project root
env_path = os.path.join(project_root, '.env')
load_dotenv(env_path)

import json
from datetime import datetime, timedelta
from database import SessionLocal, Company, AiEnrichmentProposal, User
import gemini_service

def main():
    # Initialize Gemini - use flash-lite to avoid quota issues
    gemini_service.init_gemini_service(model='flash-lite')

    db = SessionLocal()
    try:
        company = db.query(Company).filter_by(id=12).first()
        admin_user = db.query(User).filter_by(is_admin=True).first()

        if not company:
            print('Firma nie znaleziona')
            return 1

        print(f'Test AI enrichment dla: {company.name}')
        print(f'Website: {company.website}')

        service = gemini_service.get_gemini_service()
        if not service:
            print('Brak usługi Gemini')
            return 1

        prompt = f'''Przeanalizuj firmę: {company.name}
Strona: {company.website}
Opis: {company.description_short or 'brak'}

Wygeneruj JSON z informacjami o firmie:
{{"business_summary": "opis działalności 1-2 zdania", "services_list": ["usługa1", "usługa2", "usługa3"], "industry_tags": ["tag1", "tag2"]}}
Odpowiedz TYLKO JSON bez markdown.'''

        print('Wysyłam zapytanie do Gemini...')
        response = service.generate_text(
            prompt=prompt,
            temperature=0.7,
            feature='ai_enrichment_test',
            user_id=admin_user.id if admin_user else 1,
            company_id=company.id
        )
        print(f'Odpowiedź Gemini ({len(response)} znaków)')

        # Parse response
        clean = response.strip()
        if clean.startswith('```'):
            parts = clean.split('```')
            if len(parts) > 1:
                clean = parts[1]
                if clean.startswith('json'):
                    clean = clean[4:]
        clean = clean.strip()

        try:
            ai_data = json.loads(clean)
            print(f'Parsed data: {json.dumps(ai_data, indent=2, ensure_ascii=False)[:500]}')
        except json.JSONDecodeError as e:
            print(f'Błąd parsowania JSON: {e}')
            print(f'Raw response: {response[:300]}')
            return 1

        # Create proposal
        proposal = AiEnrichmentProposal(
            company_id=company.id,
            status='pending',
            proposal_type='ai_enrichment',
            data_source=company.website,
            proposed_data=ai_data,
            ai_explanation='Test AI enrichment - propozycja wzbogacenia danych',
            confidence_score=0.85,
            expires_at=datetime.utcnow() + timedelta(days=30)
        )
        db.add(proposal)
        db.commit()

        print(f'\n✅ Utworzono propozycję ID: {proposal.id}')
        print(f'Status: {proposal.status}')
        print(f'Data wygaśnięcia: {proposal.expires_at}')

        return 0

    finally:
        db.close()

if __name__ == '__main__':
    sys.exit(main())
