import sqlite3
import os
import json
import requests
import argparse
from dotenv import load_dotenv

# --- Configuration & Setup ---
load_dotenv(dotenv_path="/home/node/clawd/.env", override=True)
DB_PATH = "/home/node/clawd/repos/brancheneinstufung2/company_explorer_local.db"
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")

class SniperGenerator:
    def __init__(self, db_path=DB_PATH):
        self.db_path = db_path

    def get_lead_data(self, company_id):
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM companies WHERE id = ?", (company_id,))
        company_data = cursor.fetchone()
        conn.close()
        return dict(company_data) if company_data else None

    def generate_copy(self, company_id, target_role="Wirtschaftl. Entscheider"):
        lead_data = self.get_lead_data(company_id)
        if not lead_data: return "Error: Company data not found."
        
        prompt = f"""
        Du bist ein Weltklasse B2B-Stratege. Erstelle eine 3-Satz-E-Mail-Einleitung.
        Firma: {lead_data.get('name')}
        Branche: {lead_data.get('industry_ai')}
        Rolle: {target_role}
        """
        
        headers = {"Content-Type": "application/json"}
        payload = {"contents": [{"parts": [{"text": prompt}]}]}
        url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={GEMINI_API_KEY}"
        
        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=20)
            resp.raise_for_status()
            return resp.json()['candidates'][0]['content']['parts'][0]['text'].strip()
        except Exception as e:
            return f"Error: {e}"

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("company_id", type=int)
    args = parser.parse_args()
    sniper = SniperGenerator()
    print(sniper.generate_copy(args.company_id))
